<template>
  <view class="container">
    加速度{{ cc }}
    <img src="/images/r.jpg" class="bg" alt="" />
    <canvas
      id="joystick"
      type="2d"
      class="joystick-canvas"
      style="width: 100%; height: 100%;"
      @touchstart="onTouchStart"
      @touchend="onTouchEnd"
    ></canvas>
  </view>
</template>

<script>
export default {
  data() {
    return {
      canvas: null,
      ctx: null,
      rod: {
        baseX: 120, // 鱼竿底部位置
        baseY: 500,
        length: 250, // 鱼竿长度
        angle: -45, // 初始角度（向左上）
      },
      floatY: 400, // 浮漂初始Y
      floatDir: 1, // 浮漂上下方向
      isCasting: false, // 是否正在抛竿动画
      castProgress: 0, // 抛竿动画进度
      cWidth:0,
      cHeight:0,
      cc:[]
    };
  },
  methods: {
    async initCanvas() {
      const info = await  uni.getSystemInfoSync();
      const { screenWidth, screenHeight, pixelRatio } = info;
      console.log(screenWidth, screenHeight, pixelRatio)
      const query = uni.createSelectorQuery().in(this);
      query.select("#joystick").node().exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext("2d");
        const dpr = pixelRatio || 1;

        canvas.width = screenWidth * dpr;
        canvas.height = screenHeight * dpr;
        console.log(canvas.width, canvas.height)
        this.cWidth = canvas.width
        this.cHeight = canvas.height
        ctx.scale(dpr, dpr);

        this.canvas = canvas;
        console.log(this.canvas)
        this.ctx = ctx;
        // this.drawScene();
        setTimeout(() => {
          this.drawScene();
        }, 100);
      });
    },

    // 主循环
    drawScene() {
      const ctx = this.ctx;
      if (!ctx) return;

      const { baseX, baseY, length, angle } = this.rod;
      ctx.clearRect(0, 0, this.cWidth, this.cHeight);

      // === 鱼竿线条 ===
      ctx.save();
      ctx.strokeStyle = "#3e2c1c";
      ctx.lineWidth = 5;
      ctx.lineCap = "round";

      // 计算鱼竿末端坐标
      const endX = baseX + Math.cos((angle * Math.PI) / 180) * length;
      const endY = baseY + Math.sin((angle * Math.PI) / 180) * length;

      // 鱼竿
      ctx.beginPath();
      ctx.moveTo(baseX, baseY);
      ctx.lineTo(endX, endY);
      ctx.stroke();

      // 鱼线
      ctx.strokeStyle = "#aaa";
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.moveTo(endX, endY);

      const lineEndY =
        this.floatY +
        (this.isCasting ? Math.sin(this.castProgress * Math.PI) * 100 : 0);

      ctx.lineTo(endX, lineEndY);
      ctx.stroke();

      // 浮漂
      ctx.fillStyle = "#ff3333";
      ctx.beginPath();
      ctx.arc(endX, lineEndY, 6, 0, Math.PI * 2);
      ctx.fill();

      ctx.restore();

      // === 浮漂上下轻微浮动 ===
      if (!this.isCasting) {
        this.floatY += this.floatDir * 0.3;
        if (this.floatY > 410 || this.floatY < 390) {
          this.floatDir *= -1;
        }
      }

      // === 抛竿动画 ===
      if (this.isCasting) {
        this.castProgress += 0.02;
        this.rod.angle = -45 + Math.sin(this.castProgress * Math.PI) * 60;
        if (this.castProgress >= 1) {
          this.isCasting = false;
          this.rod.angle = -45;
        }
      }

      this.canvas.requestAnimationFrame(this.drawScene);
    },

    onTouchStart() {
      // 开始抛竿动画
      if (!this.isCasting) {
        this.isCasting = true;
        this.castProgress = 0;
      }
    },
    onTouchEnd() {
      // 结束后自动回到待机状态
    },
  },

  mounted() {
    setTimeout(() => {
        this.initCanvas();
        uni.startAccelerometer({
    interval: 'normal', // 可选：game（20ms）、ui（60ms）、normal（200ms）
    success() {
      console.log('✅ 加速度监听已开启');
    }
  });

  // 监听加速度变化
    uni.onAccelerometerChange((res) => {
        // res 包含三个方向的加速度，单位 m/s²
        const { x, y, z } = res;
        console.log('当前加速度：', x, y, z);
        this.cc = res
        // 计算重力方向或倾斜角（例如控制canvas中鱼竿的角度）
        const angle = Math.atan2(y, x) * (180 / Math.PI);
        // 例如：this.rod.angle = -angle;
    });
    }, 100);
  },
};
</script>

<style lang="less" scoped>
.container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 0;

  .bg {
    width: calc(100vw + 260rpx);
    height: 100vh;
    object-fit: cover;
    margin-left: -130rpx;
  }

  .joystick-canvas {
    position: absolute;
    top: 0;
    left: 0;
  }
}
</style>
